﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HikVisionTool.Helper;
using HikVisionTool.DAL;
using CommomDetec;
using System.Net.Sockets;
using Newtonsoft.Json;
using System.Net;
using  HikVisionTool.Model;
using System.Threading;
using HikVisionTool.TcpServer;
using System.Windows.Threading;
using System.IO;
using System.Collections.ObjectModel;

namespace 通用过站与数采
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
         CommonDetecHelper commonDetecHelper = null;//通用检测协议解析帮助类
         AsyncTCPServer server = new AsyncTCPServer(9999);
        HikVisonDAL hikVisonDAL = new HikVisionTool.DAL.HikVisonDAL();
        private UserDAL userDAL = new UserDAL();
        SolidColorBrush WaitColor = new SolidColorBrush(Colors.Gold);
        SolidColorBrush PassColor = new SolidColorBrush(Colors.LightGreen);
        SolidColorBrush OkColor = new SolidColorBrush(Colors.ForestGreen);
         SolidColorBrush NgColor = new SolidColorBrush(Colors.Tomato);
        DispatcherTimer timer1 = new DispatcherTimer();
        DispatcherTimer timer2 = new DispatcherTimer();
        public string line = "";
        public string Jiwei = "";
        public int pline = 0;
        // 供应商编号，固定值
        public string lifnr = "105464";
        // 工序编号，固定值
        public string processid = "";
        // 扫描工位，固定值
        //public string wkposition = "高清网络检测";
        public string order = "";

        BLL.HikDataBLL hikDataBLL;
        //BLL.MesBLL mesBLL = new BLL.MesBLL();

        object listLock = new object();
        object upLock = new object();
        List<Sql2Helper.t_Item> t_Items = new List<Sql2Helper.t_Item>();
        //List<Sql8Helper.t_org_tree> t_org_trees = new List<Sql8Helper.t_org_tree>();
        ViewModel.MainViewModel viewModel = new ViewModel.MainViewModel();
        //public MesTool.Model.UserModel userModel = null;
        public Sql2Helper.t_DD_UserDetail userModel = null;
        bool isQimi = false;
        bool isZhuangpei = false;


        //THT通用测试
        //THT加密升级
        //高清网络检测
        public string operation = "高清网络检测";

        public MainWindow()
        {
            HandyControl.Tools.ConfigHelper.Instance.SetLang("zh-cn");
            InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.Manual;
            this.Left = 0;
            this.Top = 0;
            this.Title = operation + "过站与数采";
        }
        private void InitLines()
        {
            ComboBoxWkPosition.Items.Add(operation);
            if (operation.Contains( "高清"))
            {
                TextBlockJiWei.Text = "工  序";
                t_Items = hikVisonDAL.GetIPCLines().OrderBy(it => it.itemName.Length).ThenBy(it => it.itemName).ToList();
                TextBoxJiWei.Visibility = Visibility.Hidden;
                RadioButtonQiMi.Visibility = Visibility.Visible;
                RadioButtonZhuangPei.Visibility = Visibility.Visible;
                foreach (var item in t_Items)
                {
                    ComboBoxLine.Items.Add(item.itemName);
                }
            }
            if(operation.Contains("THT"))
            {
                bool flag = this.operation == "THT通用测试";
                if (flag)
                {
                    this.ComboBoxLine.Items.Add("测试3线");
                }
                bool flag2 = this.operation == "THT加密升级";
                if (flag2)
                {
                    this.ComboBoxLine.Items.Add("测试2线");
                }
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                InitLines();

                Dictionary<string, string> dic = ConfigHelper.ReadAll();
                //TextBoxName.Text = dic["name"];
                ComboBoxLine.SelectedValue = dic["line"];
                ComboBoxWkPosition.SelectedValue = dic["wkposition"];
                TextBoxJiWei.Text = dic["jiwei"];
                TCPInit(0);
                viewModel.Enable = true;
                viewModel.Items = new ObservableCollection<ViewModel.MainViewModel.Item>();
                timer1.Tick += new EventHandler(timer1_Tick);
                timer1.Interval = new TimeSpan(20000000);
                timer2.Tick += new EventHandler(timer2_Tick);
                timer2.Interval = new TimeSpan(300000000);
                hikDataBLL = new BLL.HikDataBLL(this);
                this.DataContext = viewModel;
               
                //string serial = "J53146827";
                //string errMsg = "";
                //string wknum = "";
                //operation = "高清网络检测";
                //string name = MesTool.UserBLL.GetUserName("101288", ref errMsg);
                //bool isPass = mesBLL.OperationCheck(serial, operation, ref errMsg, ref wknum);
                //if (isPass == false)
                //{
                //    return;
                //}
                //MesTool.Model.HttpModel.CheckdataDto checkdataPost = new MesTool.Model.HttpModel.CheckdataDto()
                //{
                //    serial_number = serial,
                //    operation_name = operation,
                //    user_name = name,
                //    quality ="OK",
                //};
                //isPass = mesBLL.PostCheckdata(checkdataPost, ref errMsg);
                //if (isPass == false)
                //{
                //    errMsg = "过站记录保存失败，请重新测试\r\n" + errMsg;
                //    return;
                //}
                //MesTool.Model.HttpModel.BarcodestatusDto barcodestatusPost = new MesTool.Model.HttpModel.BarcodestatusDto
                //{
                //    serial_number = serial,
                //    operation_name = operation,
                //    quality = "OK",
                //};
                //isPass = mesBLL.PostBarcodestatus(barcodestatusPost, ref errMsg);
                //if (isPass == false)
                //{
                //    errMsg = "更新序列号状态失败，请重新测试\r\n" + errMsg;
                //    return;
                //}
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("SQL"))
                {
                    HandyControl.Controls.MessageBox.Error("数据库连接异常");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error(ex.Message);
                }
                FileHelper.WriteLog(ex.ToString());
            }
        }
        bool change = false;
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                Dispatcher.Invoke(() =>
                {
                    if (viewModel.Items.Count > 0 && change)
                    {
                        Thread.Sleep(10);
                        SetPie();
                        //List.ScrollIntoView(List.Items[List.Items.Count - 1]);
                        TextBoxOrder.Text = order;
                        change = false;
                    }
                });
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
                FileHelper.WriteLog(ex.ToString());
            }
        }
        bool isLock = false;
        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                if (isLock)
                {
                    return;
                }
                lock (upLock)
                {
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            isLock = true;
                            if (hikVisonDAL.sql3Helper.SqlCheck() == false)
                            {
                                return;
                            }
                            if (operation == "THT通用测试")
                            {
                                hikDataBLL.UpOfflineData2();
                            }
                            if (operation == "THT加密升级")
                            {
                                hikDataBLL.UpOfflineData();
                            }
                            //if (operation.Contains("高清"))
                            //{
                            //    hikDataBLL.UpOfflineData();
                            //}
                        }
                        catch (Exception ex)
                        {
                            FileHelper.WriteLog(ex.ToString());
                        }
                        isLock = false;
                    });
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
                FileHelper.WriteLog(ex.ToString());
            }
        }
        private void BorderStart_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (PackIconStart.Kind == MaterialDesignThemes.Wpf.PackIconKind.Play)
                {
                    if (ComboBoxLine.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先选择线别!");
                        return;
                    }
                    if (ComboBoxWkPosition.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先选择工位!");
                        return;
                    }
                    if (operation.Contains("THT"))
                    {
                        if (TextBoxJiWei.Text == "")
                        {
                            HandyControl.Controls.MessageBox.Warning("请先输入机位!");
                            return;
                        }
                        if (int.TryParse(TextBoxJiWei.Text, out int a) == false)
                        {
                            HandyControl.Controls.MessageBox.Warning("机位输入错误!");
                            return;
                        }
                    }
                    if (TextBoxName.Text.Trim() == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先输入工号!");
                        return;
                    }
                    string err = "";
                    userModel = userDAL.GetUser(TextBoxName.Text.Trim());
                    if (userModel == null)
                    {
                        HandyControl.Controls.MessageBox.Error("姓名获取失败");
                        return;
                    }
                   
                    line = ComboBoxLine.Text;
                    TextBoxName.Text = userModel.username;
                    operation = ComboBoxWkPosition.Text;

                    if (operation == "THT通用测试" || operation == "THT加密升级")
                    {
                        this.pline = ((this.operation == "THT通用测试") ? 145 : 119);
                        processid = "641";
                        Jiwei = TextBoxJiWei.Text;
                    }
                    if (operation.Contains("高清"))
                    {
                        pline = t_Items[ComboBoxLine.SelectedIndex].id;
                        processid = "050";
                        isQimi = RadioButtonQiMi.IsChecked == true;
                        isZhuangpei = RadioButtonZhuangPei.IsChecked == true;
                    }

                    viewModel.Enable = false;
                    BorderStart.Background = NgColor;
                    PackIconStart.Kind = MaterialDesignThemes.Wpf.PackIconKind.Stop;
                    PoptipStart.Content = "停止采集";
                    server.Start();
                    timer1.Start();
                    bool flag14 = this.operation == "THT通用测试" || this.operation == "THT加密升级";
                    if (flag14)
                    {
                        this.timer2.Start();
                    }
                }
                else
                {
                    if (userModel != null)
                    {
                        TextBoxName.Text = userModel.jobnumber;
                    }
                    viewModel.Enable = true;
                    BorderStart.Background = OkColor;
                    PackIconStart.Kind = MaterialDesignThemes.Wpf.PackIconKind.Play;
                    PoptipStart.Content = "开始采集";
                    server.Stop();
                    timer1.Stop();
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("SQL"))
                {
                    HandyControl.Controls.MessageBox.Error("数据库连接异常");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error(ex.Message);
                }
                FileHelper.WriteLog(ex.ToString());
            }
        }

        private void BorderStart_MouseMove(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        private void BorderStart_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            bool wait = false;
            lock (listLock)
            {
                foreach (var item in viewModel.Items)
                {
                    if (item.BackColor != WaitColor && item.Pk_id == null)
                    {
                        wait = true;
                        break;
                    }
                }
            }
            if (wait == true)
            {
                MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Ask("还有未上传的数据，是否退出？");
                if (messageBoxResult != MessageBoxResult.OK)
                {
                    e.Cancel = true;
                }
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            ConfigHelper.Write("wkposition", ComboBoxWkPosition.Text);
            ConfigHelper.Write("line", ComboBoxLine.Text);
            ConfigHelper.Write("jiwei", TextBoxJiWei.Text);
            if (userModel != null)
            {
                ConfigHelper.Write("name", userModel.jobnumber);
            }
            System.Environment.Exit(0);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            order = "";
            TextBoxOrder.Text = order;
        }

        public void SetPie()
        {
            int pass = 0;
            int fail = 0;
            lock (listLock)
            {
                foreach (var item in viewModel.Items)
                {
                    if (item.BackColor == NgColor)
                    {
                        fail++;
                    }
                    if (item.BackColor == PassColor || item.BackColor == OkColor)
                    {
                        pass++;
                    }
                }
            }
            if (viewModel.Pass[0] != pass || viewModel.Fail[0] != fail)
            {
                viewModel.Pass[0] = pass;
                viewModel.Fail[0] = fail;
            }
        }
        public void SetList(string serial, string wknum)
        {
            Dispatcher.Invoke(() =>
            {
                lock (listLock)
                {
                    ViewModel.MainViewModel.Item item = new ViewModel.MainViewModel.Item()
                    {
                        No = viewModel.Items.Count + 1,
                        MoCode = wknum,
                        BarCode = serial,
                        BackColor = WaitColor,
                        Pk_id = null
                    };
                    if (viewModel.Items.Count > 0)
                    {
                        var model = viewModel.Items.Where(it => it.BarCode == serial).FirstOrDefault();
                        if (model == null)
                        {
                            viewModel.Items.Add(item);
                            List.ScrollIntoView(List.Items[item.No - 1]);
                        }
                        else
                        {
                            model.Pk_id = null;
                            model.BackColor = WaitColor;
                            List.ScrollIntoView(List.Items[model.No - 1]);
                        }
                    }
                    else
                    {
                        viewModel.Items.Add(item);
                        List.ScrollIntoView(List.Items[item.No - 1]);
                    }
                }
            });
        }

        public void TCPInit(int type)
        {
            try
            {
                commonDetecHelper = new CommonDetecHelper(type, dataHandler);//通用检测协议解析帮助类
                server.ClientConnected += new EventHandler<AsyncEventArgs>(server_ClientConnected);
                server.ClientDisconnected += new EventHandler<AsyncEventArgs>(server_ClientDisconnected);
                server.DataReceived += new EventHandler<AsyncEventArgs>(DataReviced);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void dataHandler(TcpClient client, string data)
        {
            try
            {
                bool isPass = true;
                string errMsg = "";
                SocketTransferData transData = JsonConvert.DeserializeObject<SocketTransferData>(data);
                string serial = String.Empty;

                switch (transData.Name)
                {
                    case "VerifyData"://校验命令
                        VerifyData verifyData = JsonConvert.DeserializeObject<VerifyData>(transData.Data);
                        serial = verifyData.Serial;
                        //dosomething: 做序列号校验（工序），无校验则直接响应成功
                        string wknum = "";
                        if (operation.Contains("THT"))
                        {
                            wknum = serial.Substring(0, 10);
                            isPass = hikVisonDAL.CheckWknum(ref order, wknum, ref errMsg);
                            if (isPass == false)
                            {
                                break;
                            }
                        }
                        if (operation.Contains("高清"))
                        {
                            wknum = hikVisonDAL.GetWkNum(serial);
                            isPass = hikVisonDAL.CheckWknum(ref order, wknum, ref errMsg);
                            if (isPass == false)
                            {
                                break;
                            }
                            isPass = hikVisonDAL.CheckHDGuoZhan(isQimi, isZhuangpei, serial, line, ref errMsg);
                            if (isPass == false)
                            {
                                break;
                            }
                        }

                        SetList(serial, wknum);
                        break;
                    case "DetectionResult"://检测结果命令
                        DetectionResult detectionResult = JsonConvert.DeserializeObject<DetectionResult>(transData.Data);
                        serial = detectionResult.Serial;
                        //dosomething:  可以根据detectionResult，调接口将检测结果存后台
                        string pk = "";
                        ViewModel.MainViewModel.Item item1 = null;
                        lock (listLock)
                        {
                            item1 = viewModel.Items.Where(it => it.BarCode == serial).FirstOrDefault();
                            DateTime time = DateTime.Now;
                            pk = $"{lifnr}{serial}{time.ToString("yyyyMMddHHMMssfff")}";
                            if (item1 != null)
                            {

                                if (detectionResult.Result.Equals(ResultStatus.SUCCESS))
                                {
                                    #region 
                                    if (operation.Contains("高清"))
                                    {
                                        StringBuilder sb = new StringBuilder();
                                        foreach (var subItem in detectionResult.CheckSubItems)
                                        {
                                            sb.AppendLine(subItem.ID + ":" + subItem.Name + ":" + subItem.Description + ":" + subItem.Result.ToString());
                                        }
                                        isPass = hikVisonDAL.UpHDGuoZhan(serial, userModel.username, sb.ToString());
                                        if (isPass == false)
                                        {
                                            item1.BackColor = NgColor;
                                            errMsg = "过站数据上传失败，请重新测试";
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        Sql2Helper.hkws hkws = new Sql2Helper.hkws()
                                        {
                                            MoCode = item1.MoCode,
                                            plcode = line,
                                            Jiwei = int.Parse(Jiwei),
                                            Gongwei = userModel.username,
                                            prodBarCode = serial
                                        };
                                        hkws.id_wo = int.Parse(time.ToString("yyyyMMdd"));
                                        hkws.createTime = time;
                                        Task.Factory.StartNew(() =>
                                        {
                                            try
                                            {
                                                Sql8Helper.order_work order_Work = hikVisonDAL.GetPlanMain(hkws.MoCode);
                                                if (order_Work == null)
                                                {
                                                    HandyControl.Controls.MessageBox.Error("未获取到" + hkws.MoCode + "的订单信息", this.Title);
                                                    return;
                                                }
                                                hkws.ProduceModel = order_Work.material_name;
                                                //2.2
                                                hikVisonDAL.UpTHTGuoZhan(hkws);
                                                if (operation == "THT通用测试")
                                                {
                                                    //sql 10 边缘数据库
                                                    hikVisonDAL.UpTHTGuoZhan2(hkws);
                                                }
                                                //hikVisonDAL.UpPlanDetail(t_Proc_Plan_Main.id, hkws.createTime.ToString("yyyy-MM-dd"));
                                            }
                                            catch (Exception ex)
                                            {
                                                string hkwsJson = JsonConvert.SerializeObject(hkws);
                                                FileHelper.WriteJson(hkwsJson, "过站数据", hkws.prodBarCode + ".txt");
                                                FileHelper.WriteLog(ex.ToString());
                                            }
                                        });
                                    }
                                    #endregion
                                    item1.BackColor = PassColor;
                                }
                                else
                                {
                                    item1.BackColor = NgColor;
                                }
                            }
                        }
                        Task.Factory.StartNew(() =>
                        {
                            if (item1 != null)
                            {
                                hikDataBLL.PostHikDate(detectionResult, item1.MoCode, pk);
                            }
                            item1.Pk_id = pk;
                            change = true;
                        });
                        break;
                }

                byte[] responsedata = commonDetecHelper.BuildSucessResponse(transData.Name, serial);//成功响应
                if (isPass == false)
                {
                    responsedata = commonDetecHelper.BuildFaildResponse(transData.Name, serial, errMsg);//失败响应
                }
                server.Send(client, responsedata);

                change = true;
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
                FileHelper.WriteLog(ex.ToString());
            }
        }

        public void server_ClientConnected(object sender, AsyncEventArgs e)
        {
            IPEndPoint endpoint = (IPEndPoint)e._state.TcpClient.Client.RemoteEndPoint;
        }

        public void server_ClientDisconnected(object sender, AsyncEventArgs e)
        {
            IPEndPoint endpoint = (IPEndPoint)e._state.TcpClient.Client.RemoteEndPoint;
        }


        public void DataReviced(object sender, AsyncEventArgs e)
        {
            IPEndPoint endpoint = (IPEndPoint)e._state.TcpClient.Client.RemoteEndPoint;
            AsyncTCPServer sevice = sender as AsyncTCPServer;
            commonDetecHelper.RecovedSocketData(e._state.TcpClient, e._state.Buffer, 0, e._state.ReciveDataSize);
        }

        private void ComboBoxLine_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //pline = t_Items[ComboBoxLine.SelectedIndex].id;
        }
    }
}
